package OptimalAlgorithm.Simulation;
//https://leetcode.cn/problems/zigzag-conversion/
public class Convert {
    public String convert(String s, int numRows) {
        //处理特殊情况
        if (numRows == 1) {
            return s;
        }
        char[] ch = s.toCharArray();
        int d = 2 * numRows - 2;
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i <= numRows - 1; i++) {
            //拼首行
            if(i == 0){
                int j = 0;
                while (j < s.length()){
                    ret.append(ch[j]);
                    j += d;
                }
            }
            //拼第k行
            if(i != 0 && i != numRows - 1){
                for (int j = i,a = d - i; j < s.length(); j += d,a += d) {
                    ret.append(ch[j]);
                    if(a < s.length()){
                        ret.append(ch[a]);
                    }
                }
            }
            //拼最后一行
            if(i == numRows - 1){
                for (int j = numRows - 1; j < s.length(); j += d) {
                    ret.append(ch[j]);
                }
            }
        }
        return String.valueOf(ret);
    }
}
